package ru.hh.school.persistence;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class ConnectionFromPool {
    private final Connection connection;
    private final ConnectionPool connectionPool;
    private boolean isClosed = false;

    public ConnectionFromPool(Connection connection, ConnectionPool connectionPool) {
        this.connection = connection;
        this.connectionPool = connectionPool;
    }

    public PreparedStatement prepareStatement(String sql) throws SQLException {
        shouldNotBeClosed();
        return connection.prepareStatement(sql);
    }

    public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
        shouldNotBeClosed();
        return connection.prepareStatement(sql, autoGeneratedKeys);
    }

    public void close() {
        isClosed = true;
        connectionPool.freeConnection(connection);
    }

    private void shouldNotBeClosed() {
        if (isClosed) {
            throw new IllegalStateException("Connection already closed");
        }
    }

    // guard
    @Override
    protected void finalize() throws Throwable {
        if (!isClosed) {
            close();
        }
        super.finalize();
    }
}